package net.zhengxinyun.performance.App.appCtrl;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.dto.examDTO.ExamDTO;
import net.zhengxinyun.performance.entity.exam.*;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.filter.exam.*;
import net.zhengxinyun.performance.service.examNew.*;
import net.zhengxinyun.performance.service.login.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/app/exam")
public class ExamTestCtrl {

    @Autowired
    private UnSysUserService examUsersService;
    @Autowired
    private InquireObjService inquireService;

    @Autowired
    private PingYiService pingYiService;

    @Autowired
    private QuestionnaireService questionService;

    @Autowired
    private PaperService paperService;
    @Autowired
    private UserService userService;

    /**
     * 测评对象管理 获取所有测评对象
     *
     * @return
     */
    @PostMapping("/userManage")
    public Result<HashMap<String, Object>> userManage(@RequestBody UnSysUserFilter filter) {


        String optionType = filter.getOptionType();

        UnSysUsers record = new UnSysUsers();
        record.setUserName(filter.getUserName());
        record.setUserSex(filter.getUserSex());
        record.setUserType(filter.getUserType());
        record.setUserTel(filter.getUserTel());

        switch (optionType) {

            case "query":
                List<UnSysUserFilter> unSysUsers1 = examUsersService.seletListUsers(filter);
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", unSysUsers1);
                return ResultUtils.getSuccessResults(map);
            case "add":

                record.setId(null);
                int insert = examUsersService.insert(record);
                break;
            case "update":
                record.setId(filter.getId());
                if (ObjectUtils.isBlank(record.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "用户id不能为空", null);
                }
                examUsersService.updateByPrimaryKey(record);
                break;
            case "del":
                record.setId(filter.getId());
                record.setId(filter.getId());
                if (ObjectUtils.isBlank(record.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "用户id不能为空", null);
                }
                examUsersService.deleteByPrimaryKey(record.getId());
                break;
            default:
                return ResultUtils.getResults(Result.Status.ERROR, "optionType参数错误", null);

        }


        return ResultUtils.getSuccessResults(null);
    }

    /**
     * 用户类型管理
     *
     * @return
     */

    @PostMapping("/userTypeManage")
    public Result<HashMap<String, Object>> userTypeManage(@RequestBody UsersTypeFilter filer) {
        String optionType = filer.getOptionType();
        UserTypeEntity record = new UserTypeEntity();
        record.setUserType(filer.getUserType());
        switch (optionType) {
            case "query":
                List<UserTypeEntity> typeLists = examUsersService.seletListTypes(filer);
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", typeLists);
                return ResultUtils.getSuccessResults(map);
            case "del":
                if (ObjectUtils.isBlank(filer.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "用户id不能为空", null);
                }
                int i = examUsersService.deleteTypeByPrimaryKey(filer.getId());
                break;
            case "update":
                record.setId(filer.getId());
                examUsersService.updateTypeByPrimaryKeySelective(record);
                break;
            case "add":
                record.setId(null);
                examUsersService.insertType(record);
                break;
        }


        return ResultUtils.getSuccessResults(null);
    }

    /**
     * 调查对象总表
     */
    @PostMapping("/inquireObj")
    public Result<HashMap<String, Object>> inquireObj(@RequestBody InquireObjFilter filter) {
        String optionType = filter.getOptionType();
        InquireObjEntity record = new InquireObjEntity();

        record.setInquireName(filter.getInquireName());
        record.setInquireSource(filter.getInquireSource());

        switch (optionType) {
            case "query":
                List<InquireObjEntity> inquireObjEntities = inquireService.selectListObjs(filter);
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", inquireObjEntities);
                System.out.println("------/inquireObj");
                return ResultUtils.getSuccessResults(map);
            case "del":
                if (ObjectUtils.isBlank(filter.getInqId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "id不能为空", null);
                }
                inquireService.deleteObjByPrimaryKey(filter.getInqId());
                break;
            case "update":
                record.setId(filter.getInqId());
                inquireService.updateObjByPrimaryKeySelective(record);
                break;
            case "add":

                record.setId(null);
                inquireService.insertObj(record);
                break;
        }

        System.out.println("-----/inquireObj");
        return ResultUtils.getSuccessResults(null);
    }


    /**
     * 调查对象信息 （抽取调查人员）
     */
    @PostMapping("/inquireInfo")
    public Result<HashMap<String, Object>> inquireInfo(@RequestBody InquireObjFilter filter) {
        String optionType = filter.getOptionType();
        InquireInfoEntity record = new InquireInfoEntity();
        record.setInqId(filter.getInqId());
        record.setUserId(filter.getUserId());
        switch (optionType) {
            case "query":

                List<InquireObjFilter> inquireInfoEntities = inquireService.selectListInfos(filter);
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", inquireInfoEntities);
                System.out.println("------/inquireInfo");
                return ResultUtils.getSuccessResults(map);
            case "del":
                if (StringUtils.isBlank(filter.getInqInfoIds())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "InqId不能为空", null);
                }
                List<String> strings = Util.strToList(filter.getInqInfoIds());
                for (String inqId : strings) {
                    inquireService.deleteInfoByPrimaryKey(new Long(inqId));

                }

                break;
            case "update":
                record.setId(filter.getInqInfoId());
                inquireService.updateInfoByPrimaryKeySelective(record);
                break;
            case "add":
                String userIdLists = filter.getUserIdLists();
                if (StringUtils.isBlank(userIdLists)||ObjectUtils.isBlank(filter.getInqId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "调查总表的Id和用户勾选列表userIdlists不能为空", null);
                }

                List<String> ids = Util.strToList(userIdLists);
                List<InquireInfoEntity> listRecord = new ArrayList<>();

                for (String id : ids) {

                    InquireInfoEntity recorditem = new InquireInfoEntity();
                    recorditem.setUserId(Integer.parseInt(id));
                    recorditem.setInqId(filter.getInqId());
                    recorditem.setId(null);
                    listRecord.add(recorditem);
                }

                int i = inquireService.insertInfo(listRecord);
                break;
        }

        System.out.println("-------/inquireInfo");
        return ResultUtils.getSuccessResults(null);
    }

    /**
     * 抽选规则
     * 确定用户来源后；
     * 可以先选择用户类型，在选择抽选规则，按照随机，或者特定规则筛选；
     *
     * @return
     */
    @PostMapping("/chooseObjs")
    public Result<HashMap<String, Object>> chooseInquireObj(@RequestBody InquireObjFilter filter) {

        String rulesType = filter.getRulesType();
        String rulesNum = filter.getRulesNum();
        String inquireSource = filter.getInquireSource();
        String rulesTotal = filter.getRulesTotal();
        if (ObjectUtils.isBlank(rulesType) || ObjectUtils.isBlank(inquireSource)) {
            return ResultUtils.getResults(Result.Status.ERROR, "规则类型，规则数量，调查来源", null);
        }
        int rulesnums = StringUtils.isBlank(rulesNum) ? 0 : Integer.parseInt(rulesNum);
        int total = StringUtils.isBlank(rulesTotal) ? 0 : Integer.parseInt(rulesTotal);
        List<UnSysUserFilter> unSysUserFilters = inquireService.chooseRule(rulesType, rulesnums, filter.getUserType(), inquireSource, total);
        if(unSysUserFilters==null){
            return ResultUtils.getResults(Result.Status.ERROR, "规则类型参数错误", null);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("data", unSysUserFilters);
        System.out.println("------/chooseObjs");
        return ResultUtils.getSuccessResults(map);
    }


    /**
     * 问卷总表管理
     * @param filter
     * @return
     */
    @PostMapping("/wenjuanManage")
    public Result<HashMap<String, Object>> wenjuanManage(@RequestBody QuestionnaireFilter filter)
    {

        HashMap<String, Object> map = questionService.questionnaireManage(filter.getOptionType(), filter);

        return ResultUtils.getSuccessResults(map);

    }

    /**
     * 公众评议管理
     * @return
     */
    @PostMapping("/gzpymanage")
    public Result<HashMap<String, Object>> GongZhongPingYiObj(@RequestBody PingyiFilter filter)
    {


        HashMap<String, Object> stringObjectHashMap = pingYiService.managePingYi(filter, filter.getOptionType());

        return ResultUtils.getSuccessResults(stringObjectHashMap);
    }

    /**
     * 公众评议调查对象管理
     * @return
     */
    @PostMapping("/gzpyObjmanage")
    public Result<HashMap<String, Object>> gzpyObjmanage(@RequestBody PyInqObjFilter filter)
    {

        String optionType = filter.getOptionType();

        HashMap<String, Object> stringObjectHashMap = pingYiService.managePYObj(optionType, filter);

        return ResultUtils.getSuccessResults(stringObjectHashMap);

    }

    /**
     * App问卷预览
     * @return
     */
    @PostMapping("/priviewpaper")
    public Result<HashMap<String, Object>> getpyObjLists(@RequestBody ExamDTO filter)
    {
        String examType = filter.getExamType();
        Long questionnaireId = filter.getQuestionnaireId();

        List<ExamDTO> examDTOS = paperService.priviewPages(examType, questionnaireId);
        HashMap<String,Object> map = new HashMap<>();
        map.put("data",examDTOS);
        return ResultUtils.getSuccessResults(map);
    }


    /**
     * 获取公众评议问卷
     * @return
     */
    @PostMapping("/getExamPaper")
    public Result<HashMap<String, Object>> getExamPaper(@RequestBody ExamDTO filter)
    {

        Long pyObjId = filter.getPyObjId();
        Long pyId = filter.getPyId();
        ExamDTO dto = new ExamDTO();
        dto.setPyObjId(pyObjId);
        List<ExamDTO> pyInfos = pingYiService.getPYInfos(dto);
        if(ObjectUtils.isBlank(pyInfos)){
            return  ResultUtils.getResults("500","参数错误",null);
        }
        ExamDTO dto1 = pyInfos.get(0);
        String examType = dto1.getExamType();
        Long questionnaireId = dto1.getQuestionnaireId();

        Long userId  =getUserId(dto1.getInquireSource(),filter.getLoginTel());


        List<ExamDTO> examDTOS = paperService.getCachePages(examType, questionnaireId,pyId,userId);

        HashMap<String,Object> map = new HashMap<>();
        map.put("data",examDTOS);
        /**
         * 获取提交记录
         */
        int i = paperService.selecSubmintRecoreds(userId, questionnaireId, pyId,dto1.getInquireSource(), examType);

        map.put("isSubmint",i);
        return ResultUtils.getSuccessResults(map);

    }

    /**
     * 答题缓存
     * @param filter
     * @return
     */
    @PostMapping("/saveExamRecord")
    public Result<String> saveExamRecord(@RequestBody ExamDTO filter)
    {

        Long pyObjId = filter.getPyObjId();
        String resultOpt = filter.getResultOpt();
        ExamDTO dto = new ExamDTO();
        dto.setPyObjId(pyObjId);
        List<ExamDTO> pyInfos = pingYiService.getPYInfos(dto);
        ExamDTO dto1 = pyInfos.get(0);

        Long examId = filter.getExamId();
        String examType = dto1.getExamType();
        Long userId  =getUserId(dto1.getInquireSource(),filter.getLoginTel());

        int t = paperService.selecSubmintRecoreds(userId, dto1.getQuestionnaireId(), dto1.getPyId(),dto1.getInquireSource(), examType);
        if(t>0){
            return ResultUtils.getResults("500","提交过了");
        }
        int i = paperService.cacheResult(examId, dto1.getQuestionnaireId(), userId, dto1.getPyId(), dto1.getInquireSource(), examType, resultOpt);
        return ResultUtils.getSuccessResults();
    }


    /**
     * 问卷提交
     * @return
     */
    @PostMapping("/saveExamResults")
    public Result<String> saveExamResults(@RequestBody ExamDTO filter){
        Long pyObjId = filter.getPyObjId();
        String loginTel = filter.getLoginTel();


        ExamDTO dto = new ExamDTO();
        dto.setPyObjId(pyObjId);
        List<ExamDTO> pyInfos = pingYiService.getPYInfos(dto);
        ExamDTO dto1 = pyInfos.get(0);
        Long userId = getUserId(dto1.getInquireSource(),loginTel);
        int i = paperService.saveSubmintRecore(userId, dto1.getQuestionnaireId(), dto1.getPyId(), dto1.getInquireSource(), dto1.getExamType());
        if(i>0)
        {
            return ResultUtils.getSuccessResults();
        }

        return ResultUtils.getResults("500","无数据更新",null);

    }


   private  Long getUserId(String inquireSource,String loginTel){
        Long userId= null;
        if("系统".equals(inquireSource)){
            UserFilter userFilter = new UserFilter();
            userFilter.setUserPhone(loginTel);
            List<UserFilter> userFilters = userService.queryUsers(userFilter);
            userId = userFilters.get(0).getId();
        }else {
            UnSysUserFilter filter1 = new UnSysUserFilter();
            filter1.setUserTel(loginTel);
            List<UnSysUserFilter> unSysUserFilters = examUsersService.seletListUsers(filter1);
            userId = unSysUserFilters.get(0).getId();
        }
        return userId;
    }

}
